﻿using Sustainalytics.ESG.Entities;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;
using System;
using System.Linq;

namespace Sustainalytics.Synchronization.Validation.ValidationRules.Comprehensive
{
    public class LinkedIndicatorsRule : ComprehensiveRule<RPCompanyESGComputationResult>
    {
        public override Severity Severity => Severity.Yellow;
        public override BusinessResearchProduct BusinessResearchProduct => BusinessResearchProduct.Comprehensive;
        public override string Code => "YR4";
        public override string InformationalMessage => "Connection between indicators G.2.1 and G.2.2 (when G.2.1 = 0 G.2.2 = 0 needs to be aligned)";

        public LinkedIndicatorsRule()
        {
            For(x => x.Indicators).When(Validator).WithKey(x => x.Id).WithMessage("The company {0} #{1}# does not have compliant linked governance indicators");
        }

        private bool Validator(RPCompanyESGComputationResult validatedResult, RPCompanyESGComputationResult referenceResult)
        {
            var g21 = validatedResult.Indicators.FirstOrDefault(x => x.Code == "G.2.1");

            if (g21 == null)
                return true;

            if (Math.Abs(g21.RawScore) > float.Epsilon)
                return true;

            var g22 = validatedResult.Indicators.FirstOrDefault(x => x.Code == "G.2.2");

            if (g22 == null)
                return true;

            if (Math.Abs(g22.RawScore) > float.Epsilon)
                return false;

            return true;
        }
    }
}
